package org.jeecg.modules.car.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.car.CarDerateDetails;
import org.jeecg.entity.car.CarMerchantDerate;
import org.jeecg.enums.car.CarDerateDetailStatusEnum;
import org.jeecg.enums.car.CarDerateStatusEnum;
import org.jeecg.enums.car.CarDerateTypeEnum;
import org.jeecg.modules.car.entity.CarMerchant;
import org.jeecg.modules.car.mapper.CarMerchantDerateMapper;
import org.jeecg.modules.car.service.ICarDerateDetailsService;
import org.jeecg.modules.car.service.ICarMerchantDerateService;
import org.jeecg.modules.car.service.ICarMerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Description: 商户优惠券
 * @Author: jeecg-boot
 * @Date:   2020-10-22
 * @Version: V1.0
 */
@Service
@Slf4j
public class CarMerchantDerateServiceImpl extends ServiceImpl<CarMerchantDerateMapper, CarMerchantDerate> implements ICarMerchantDerateService {


    @Autowired
    private ICarMerchantService carMerchantService;

    @Autowired
    private ICarDerateDetailsService carDerateDetailsService;

    @Autowired
    private CarMerchantDerateMapper carMerchantDerateMapper;

    /**
     * 添加优惠券
     * @param carMerchantDerate
     * @param carMerchant
     */
    @Override
    @Transactional
    public void add(CarMerchantDerate carMerchantDerate, CarMerchant carMerchant) {
        this.save(carMerchantDerate);
        //更新商户账号余额
        carMerchantService.updateRemainAmount(carMerchant);  //可能需要加锁
    }

    /**
     * 商家即时减免 - 自动添加优惠券
     * @param carMerchantDerate
     * @param carMerchant
     */
    @Override
    public void addDerate(CarMerchantDerate carMerchantDerate, CarMerchant carMerchant) {
        this.save(carMerchantDerate);
        CarDerateDetails carDerateDetails = new CarDerateDetails();
        carDerateDetails.setDerateId(carMerchantDerate.getId());
        carDerateDetails.setPlateNumber(carMerchantDerate.getPlateNumber());
        carDerateDetails.setDerateAmount(carMerchantDerate.getDerateAmount());
        carDerateDetails.setTenantId(carMerchantDerate.getTenantId());
        carDerateDetails.setProjectId(carMerchantDerate.getProjectId());
        carDerateDetails.setUseTime(carMerchantDerate.getUseTime());
        carDerateDetails.setCreateBy(carMerchant.getId());
        carDerateDetails.setUpdateBy(carMerchant.getId());
        if ("0".equals(carMerchantDerate.getDerateMode())){  //全额减免 - 开闸放行
            carDerateDetails.setStatus(CarDerateDetailStatusEnum.CAR_DERATE_DETAIL_STATUS_1.getCode());
            carDerateDetails.setRemarks("商家输入全额减免");
        } else {
            carDerateDetails.setRemarks("商家输入减免");
            carDerateDetails.setStatus(CarDerateDetailStatusEnum.CAR_DERATE_DETAIL_STATUS_0.getCode());
        }
        carDerateDetailsService.save(carDerateDetails);
        //更新商户账号余额
        carMerchantService.updateRemainAmount(carMerchant);
    }

    /**
     * 编辑优惠券
     * @param carMerchantDerate
     * @param carMerchant
     */
    @Override
    @Transactional
    public void editDerate(CarMerchantDerate carMerchantDerate, CarMerchant carMerchant) {
        carMerchantDerateMapper.editDerate(carMerchantDerate);
        if (carMerchant != null){
            carMerchantService.updateRemainAmount(carMerchant);
        }
    }

    /**
     * 删除优惠券
     * @param carMerchant 商户详情
     * @param derateId 优惠券id
     * @return
     */
    @Override
    @Transactional
    public Result delDerate(CarMerchant carMerchant, String derateId) {
        //获取优惠券详情
        CarMerchantDerate carMerchantDerate = carMerchantDerateMapper.selectById(derateId);
        if (carMerchant != null){
            if (carMerchantDerate == null){
                return Result.error("未查询到当前优惠券信息");
            }
            //已发送 未使用的优惠券不允许删除
            if (carMerchantDerate.getStatus().equals(CarDerateStatusEnum.CAR_DERATE_STATUS_1.getCode())){
                return Result.error("当前优惠券状态不允许删除！");
            }
            //商家自己发放的消费券 && 状态未使用  需反还余额
            if (CarDerateTypeEnum.CAR_DERATE_TYPE_0.getCode().equals(carMerchantDerate.getDerateType()) &&
                    CarDerateStatusEnum.CAR_DERATE_STATUS_0.getCode().equals(carMerchantDerate.getStatus())){
                //优惠卷剩余次数
                Integer remainder = carMerchantDerate.getUsableNumber() - carMerchantDerate.getUsedNumber();
                if (carMerchantDerate.getDerateSource() == 0){
                    //余额生成的券
                    //商家余额 + 优惠券金额
                    carMerchant.setRemainAmount(carMerchant.getRemainAmount().add(carMerchantDerate.getDerateAmount().multiply(BigDecimal.valueOf(remainder))));
                }else {
                    //赠送余额生成的券
                    if (StringUtils.sameDate(carMerchantDerate.getCreateTime(), new Date())){
                        // 当月生成的券 返赠送余额
                        carMerchant.setDonateAmount(carMerchant.getDonateAmount().add(carMerchantDerate.getDerateAmount().multiply(BigDecimal.valueOf(remainder))));
                    }
                }
                log.info("删除优惠卷id：{}， 优惠卷次数：{}， 使用次数：{}， 退还金额：{} ， 商家余额：{}",carMerchantDerate.getId(), carMerchantDerate.getUsableNumber(), carMerchantDerate.getUsedNumber(),carMerchantDerate.getDerateAmount().multiply(BigDecimal.valueOf(remainder)));
                carMerchantService.updateRemainAmount(carMerchant);
            }
        }
        //设置优惠券为失效状态
//        carMerchantDerate.setStatus(CarDerateStatusEnum.CAR_DERATE_STATUS_MISS.getCode());
        //逻辑删除优惠券
        carMerchantDerateMapper.delDerate(carMerchantDerate);
        return Result.ok("删除成功");
    }

    @Override
    public Result batchDelDerate(List<String> derateIds) {
        List<CarMerchantDerate> derates = carMerchantDerateMapper.selectBatchIds(derateIds);
        if (derates.size() <= 0){
            return Result.error("未查询到优惠卷信息");
        }
        for (int i = 0; i < derates.size(); i++){
            //状态必须为未使用  &&  系统发放的卷才允许操作
            if (!derates.get(i).getStatus().equals(CarDerateStatusEnum.CAR_DERATE_STATUS_0.getCode()) ||
                    !derates.get(i).getDerateType().equals(CarDerateTypeEnum.CAR_DERATE_TYPE_1.getCode())){
                return Result.error("所选优惠卷中有不允许操作状态的优惠卷，请核实后再操作！");
            }else {
                derates.get(i).setStatus(CarDerateStatusEnum.CAR_DERATE_STATUS_MISS.getCode());
            }
        }
        carMerchantDerateMapper.batchDelDerate(derateIds);
        return Result.ok("删除成功！");
    }

    @Override
    public List<CarMerchantDerate> findPage(Page<CarMerchantDerate> page, CarMerchantDerate carMerchantDerate) {
        carMerchantDerate.setTenantId(SsoUtil.getLoginUser().getTenantId());
        return carMerchantDerateMapper.findPage(page, carMerchantDerate);
    }

    @Override
    public CarMerchantDerate getByPlateStatus(String plate, Integer status) {
        return carMerchantDerateMapper.getByPlateStatus(plate,status);
    }

    @Override
    public void updateUseStatus(String derateId, Integer oldStatus,Integer newStatus,Integer usedNumber) {
        carMerchantDerateMapper.updateUseStatus(derateId,oldStatus,newStatus,usedNumber);
    }

    @Override
    public List<CarMerchantDerate> derateList(Page<CarMerchantDerate> page, CarMerchantDerate carMerchantDerate) {
        return carMerchantDerateMapper.derateList(page,carMerchantDerate);
    }


}
